﻿using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace NET6.WebAPI.Attributes
{
    /// <summary>
    /// 手机号码验证特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public class PhoneNumberAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null)
            {
                return ValidationResult.Success;
            }

            string phoneNumber = value.ToString();

            bool isValid = Regex.IsMatch(phoneNumber, @"^\d{11}$"); // 11 位数字
            if (isValid)
            {
                return ValidationResult.Success;
            }

            return new ValidationResult("Invalid phone number format.");
        }
    }
}
